package com.way.controller;

import com.way.pojo.ValidationCodeParam;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * @author 魏彪
 */
@RestController
@RequestMapping("/code")
public class ValidationCodeController {

    private static final String VALIDATION_CODE_KEY_PREFIX = "SMS_";

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    @PostMapping
    public String code(@RequestBody ValidationCodeParam validationCodeParam) {
        String key = VALIDATION_CODE_KEY_PREFIX + validationCodeParam.getMobile();
        if (redisTemplate.hasKey(key)) {
            throw new RuntimeException("验证码已发送");
        }
        String code = generateCode();
        redisTemplate.opsForValue().set(key, code, 100, TimeUnit.MINUTES);
        return code;
    }

    public static String generateCode() {
        Random random = new Random();
        StringBuilder code = new StringBuilder();
        for (int i = 0; i < 6; i++) {
            int digit = random.nextInt(10);
            code.append(digit);
        }
        return code.toString();
    }
}
